package com.hzh.cusviewdemo.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hzh.cusviewdemo.Util.Config;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> {
    protected List<T> mData;
    protected final Context mContext;
    protected final LayoutInflater mInflater;

    public BaseRecyclerAdapter(Context context) {
        mData = new ArrayList<>();
        mContext = context;
        mInflater = LayoutInflater.from(context);
    }

    protected BaseRecyclerAdapter(@NonNull List<T> data, Context context) {
        mData = data;
        mContext = context;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new BaseRecyclerViewHolder(mContext, mInflater.inflate(getItemLayoutId(viewType), parent, false));
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
        if (position == mData.size()) {
            if (position != 0) {
                bindData(holder, position, mData.get(0));
            } else {
                bindData(holder, position, mData.get(position - 1));
            }
            return;
        }
        bindData(holder, position, mData.get(position));
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public int getSize() {
        return mData.size();
    }

    public List<T> getData() {
        return mData;
    }


    public void add(int pos, T item) {
        mData.add(pos, item);
        notifyDataSetChanged();
    }

    public void delete(int pos) {
        if (pos >= 0 && pos < mData.size()) {
            mData.remove(pos);
            notifyItemRemoved(pos);
            notifyItemRangeChanged(pos, mData.size() - pos);
        }
    }

    public void addAll(List<T> items) {
        addAll(mData.size(), items);
    }

    public void addAll(int position, List<T> items) {
        mData.addAll(position, items);
        notifyDataSetChanged();
    }

    public void setData(List<T> items) {
        mData = new ArrayList<>(items);
        notifyDataSetChanged();
    }

    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    abstract public void bindData(BaseRecyclerViewHolder holder, int position, T item);

    abstract public int getItemLayoutId(int viewType);

    public Context getContext() {
        return mContext;
    }
}